﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Reactive;
using System.IO;
using System.Diagnostics;
using System.Json;
using System.IO.IsolatedStorage;

namespace SevenDrops
{
    public partial class Credentials : PhoneApplicationPage
    {
        private const string KEY = "o30feq0qcaseg2e";

        public Credentials()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Credentials_Loaded);
        }

        void Credentials_Loaded(object sender, RoutedEventArgs e)
        {
            string myToken = string.Empty;
            IsolatedStorageSettings.ApplicationSettings.TryGetValue("token", out myToken);

            Debug.WriteLine(myToken);

            if (!string.IsNullOrEmpty(myToken))
            {
                NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
            }
        }

        private void LogInButton_Click(object sender, RoutedEventArgs e)
        {
            if ((!string.IsNullOrEmpty(EmailField.Text.Trim())) && (!string.IsNullOrEmpty(PasswordField.Password)))
            {
                HttpWebRequest request =
                    (HttpWebRequest)WebRequest.Create("https://api.dropbox.com/0/token?email=" + EmailField.Text + "&password=" +
                    PasswordField.Password + "&oauth_consumer_key=" + KEY);

                IObservable<WebResponse> n = Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)();

                n.Subscribe(t => { HandleResult(t);  }, ex => { Dispatcher.BeginInvoke(new Action(() => MessageBox.Show("There was an error getting the token."))); });
               
            }
            else
            {
                MessageBox.Show("Both email and password are required.");
            }
        }

        private void HandleResult(WebResponse response)
        {
            HttpWebResponse _response = (HttpWebResponse)response;

            using (StreamReader reader = new StreamReader(response.GetResponseStream()))
            {
                string a = reader.ReadToEnd();

                JsonValue jValue = JsonObject.Parse(a);

                IsolatedStorageSettings.ApplicationSettings["token"] = (string)jValue["token"];

                IsolatedStorageSettings.ApplicationSettings["secret"] = (string)jValue["secret"];

                IsolatedStorageSettings.ApplicationSettings.Save();

                
            }

            Dispatcher.BeginInvoke(new Action(() => { NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative)); }));
        }
    }
}